<template>

  <div class="record1">
      <!-- 新增tab切换（水电费和租金管理） -->
  <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane id="meterDom" label="水电表" name="first"></el-tab-pane>
    <el-tab-pane label="租金" name="second"></el-tab-pane>
  </el-tabs>
 <KeepAlive>
  <!-- 展示水电表区域 -->
  <div v-if="activeName =='first'">
    <!-- 搜索框 -->
    <div class="search">
      <el-select
        @change="search"
        clearable
        v-model="tenantId"
        placeholder="请选择租户"
      >
        <el-option
          v-for="item in tenantList"
          :key="item.tenantId"
          :label="item.tenantName"
          :value="item.tenantId"
        >
        </el-option>
      </el-select>

      <el-input
        class="elInput"
        placeholder="请输入机构订单号"
        clearable
        prefix-icon="el-icon-search"
        v-model="rechargeHuifuOrder"
      >
      </el-input>
      <el-input
        class="elInput"
        placeholder="请输入商户订单号"
        clearable
        prefix-icon="el-icon-search"
        v-model="rechargeOrder"
      >
      </el-input>
      <el-date-picker
        @change="change"
        :clearable="false"
        v-model="time"
        type="daterange"
        align="center"
        range-separator="-"
        :picker-options="pickerOptions"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
      >
      </el-date-picker>
      <el-button
      v-if="activeName=='first' "
        type="warning"
        icon="el-icon-star-on"
        @click="DialogVisibleSearch = true"
        >高级搜索</el-button
      >
      <el-button type="success" icon="el-icon-search" @click="search"
        >搜索/刷新</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-s-promotion"
        :disabled="tableData.length !== 0 ? false : true"
        @click="out"
        >导出</el-button
      >
    </div>
    <!-- 表格数据 -->
    <div class="table" ref="table">
      <el-table
      height="650"
        show-summary
        :summary-method="getSummaries"
        :data="tableData"
        ref="isExpand"
        v-loading="loading"
        border
        highlight-current-row
        stripe
        style="width: 100%"
      >
        >
        <template slot="empty">
          <el-empty description="暂无数据"></el-empty>
        </template>
        <el-table-column
          width="150"
          align="center"
          prop="meterNumber"
          label="设备表号"
        >
        </el-table-column>
        <el-table-column
          width="150"
          align="center"
          prop="landlordPhone"
          label="房东手机号"
        >
        </el-table-column>

        <el-table-column
          width="100"
          align="center"
          prop="beforeCount"
          :label="
            meterType == 1
              ? '充值前度数'
              : meterType == 2
              ? '充值前水量'
              : '充值前用量'
          "
        >
          <template slot-scope="scope">
            <el-tag>{{ scope.row.beforeCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="90"
          align="center"
          prop="rechargeFullAmount"
          label="交易金额"
        >
          <template slot-scope="scope">
            <el-tag>{{
              scope.row.rechargeFullAmount
                ? Number(scope.row.rechargeFullAmount).toFixed(2)
                : "0.00"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          align="center"
          prop="afterCount"
          :label="
            meterType == 1
              ? '充值后度数'
              : meterType == 2
              ? '充值后水量'
              : '充值后用量'
          "
        >
          <template slot-scope="scope">
            <el-tag>{{ scope.row.afterCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="90"
          align="center"
          prop="serviceCharge"
          label="手续费"
        >
          <template slot-scope="scope">
            <el-tag type="success">{{ scope.row.serviceCharge }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="120"
          align="center"
          prop="rechargeWay"
          label="充值方式"
        >
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.rechargeWay == 3"
              >微信支付</el-tag
            >
            <el-tag v-if="scope.row.rechargeWay == 4">支付宝支付</el-tag>
            <el-tag type="warning" v-if="scope.row.rechargeWay == 1"
              >现金充值</el-tag
            >
            <el-tag type="info" v-if="scope.row.rechargeWay == 2"
              >租币充值</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          align="center"
          prop="meterType"
          label="类型"
        >
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.meterType == 1">电表</el-tag>
            <el-tag v-if="scope.row.meterType == 2">水表</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          align="center"
          prop="process"
          label="交易状态"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.process == 2" type="success">成功</el-tag>
            <el-tag v-if="scope.row.process == 0" type="warning">处理中</el-tag>
            <el-tag v-if="scope.row.process == 1" type="warning">待充值</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          align="center"
          prop="tenantName"
          label="承租方"
        >
        </el-table-column>
        <el-table-column
          width="150"
          align="center"
          prop="productName"
          label="生产厂商"
        >
        </el-table-column>
        <el-table-column
          width="150"
          align="center"
          prop="rechargeOrder"
          label="商户订单"
        >
          <template slot-scope="scope">
            <el-popover
              placement="top"
              trigger="hover"
              :content="scope.row.rechargeOrder"
            >
              <span slot="reference" class="twoLineCls1">{{
                scope.row.rechargeOrder
              }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          align="center"
          prop="rechargeHuifuOrder"
          label="机构订单"
        >
          <template slot-scope="scope">
            <el-popover
              placement="top"
              trigger="hover"
              :content="scope.row.rechargeHuifuOrder"
            >
              <span slot="reference" class="twoLineCls1">{{
                scope.row.rechargeHuifuOrder
              }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
         
          width="200"
          align="center"
          prop="rechargeTime"
          label="充值时间"
        >
        </el-table-column>

        <el-table-column align="center" prop="times" label="倍率">
            <template slot-scope="scope">
                <span slot="reference" class="twoLineCls">{{
                  scope.row.times?scope.row.times:'暂无'
                }}</span>

            </template>
          </el-table-column>

          <el-table-column align="center" prop="times" label="充值用量">
            <template slot-scope="scope">
                <span slot="reference" class="twoLineCls">{{
                  scope.row.useValue?scope.row.useValue:'暂无'
                }}</span>

            </template>
          </el-table-column>
          
          <el-table-column  fixed="right" align="center" prop="times" width="200" label="充值完成时间">
            <template slot-scope="scope">

              <el-popover
                placement="top"
                trigger="hover"
                :content="scope.row.times==null ? '暂无' : scope.row.times"
              >
                <span slot="reference" class="twoLineCls">{{
                  scope.row.rechargeTime
                }}</span>
              </el-popover>

            </template>
          </el-table-column>



        
        <el-table-column fixed="right" width="100" align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="preview(scope.row)"
              >生成凭证</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-show="tableData.length !== 0"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 30, 50, 100, 150, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 高级搜索 -->
    <div class="searchMore">
      <el-dialog
        @close="closeSearch"
        :close-on-click-modal="true"
        title="搜索更多"
        :visible.sync="DialogVisibleSearch"
        width="800px"
      >
        <el-form
          :model="searchForm"
          ref="chargeForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="房东手机号">
            <el-input
              class="elInput"
              placeholder="请输入房东手机号"
              clearable
              v-model="landlordPhone"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="表号">
            <el-input
              class="elInput"
              placeholder="请输入表号"
              clearable
              v-model="meterNumber"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-select clearable v-model="meterType" placeholder="请选择表类型">
              <el-option
                v-for="item in meterTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="交易方式">
            <el-select
              multiple
              collapse-tags
              clearable
              v-model="rechargeWay"
              placeholder="请选择交易方式"
            >
              <el-option
                v-for="item in rechargeWayList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="厂商">
            <el-select
              v-model="productId"
              filterable
              clearable
              placeholder="请选择厂商"
            >
              <el-option
                v-for="item in productSelect"
                :key="item.productId"
                :label="item.productName"
                :value="item.productId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="danger" @click="cancelSearch">重 置</el-button>
          <el-button type="primary" @click="searchDialog">搜 索</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 打印预览 -->
    <div class="previewDialog">
      <el-dialog
        title="充值凭证"
        :visible.sync="previewDialogShow"
        width="50%"
        :destroy-on-close="true"
      >
        <div id="block" style="width: 100%; height: 100%">
          <table
            border="1"
            style="border-collapse: collapse; width: 100%; height: 100%"
          >
            <tr>
              <th colspan="2">充值凭证</th>
            </tr>
            <tr>
              <th>充值时间</th>
              <td style="text-align: center">
                {{ preViewData.rechargeTime }}
              </td>
            </tr>
            <tr>
              <th>表号</th>
              <td style="text-align: center">
                {{ preViewData.meterNumber }}
              </td>
            </tr>
            <tr>
              <th>充值方式</th>
              <td style="text-align: center">
                {{
                  preViewData.rechargeWay == 1
                    ? "现金充值"
                    : preViewData.rechargeWay == 2
                    ? "租币充值"
                    : preViewData.rechargeWay == 3
                    ? "微信支付"
                    : "支付宝支付"
                }}
              </td>
            </tr>
            <tr>
              <th>充值金额</th>
              <td style="text-align: center">
                {{ preViewData.rechargeFullAmount }}
              </td>
            </tr>
            <tr>
              <th>充值前用量</th>
              <td style="text-align: center">
                {{ preViewData.beforeCount }}
              </td>
            </tr>
            <tr>
              <th>充值后用量</th>
              <td style="text-align: center">
                {{ preViewData.afterCount }}
              </td>
            </tr>
            <tr>
              <th>充值单号</th>
              <td style="text-align: center">
                {{ preViewData.rechargeOrder }}
              </td>
            </tr>
            <tr>
              <th>充值结果</th>
              <td style="text-align: center">
                {{
                  preViewData.process == 0
                    ? "处理中"
                    : preViewData.process == 1
                    ? "待充值"
                    : "充值成功"
                }}
              </td>
            </tr>
            <tr>
                <th>充值用量</th>
                <td style="text-align: center">
                  {{
                    preViewData.useValue == null
                      ? "暂无"
                      : preViewData.useValue
                     
                  }}
                </td>
              </tr>
              <tr>
                <th>倍率</th>
                <td style="text-align: center">
                  {{
                    preViewData.times == null
                      ? "暂无"
                      : preViewData.times
                     
                  }}
                </td>
              </tr>

              <tr>
                <th>充值订单完成时间</th>
                <td style="text-align: center">
                  {{
                    preViewData.finishTime == null
                      ? "暂无"
                      : preViewData.finishTime
                     
                  }}
                </td>
              </tr>



          </table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="previewDialogShow = false">取 消</el-button>
          <el-button type="success" v-print="printSet">打 印</el-button>
        </span>
      </el-dialog>
    </div>
</div>
 </KeepAlive>


  <KeepAlive>
    <RentList v-if="activeName=='second'" ></RentList>
  </KeepAlive>



  </div>
</template>

<script>
import RentList from './rentList.vue'
import {
  getRecordApi,
  getProductIdApi,
  getTenantApi,
  outOrderApi
} from "../../../../api/system/meter";
import { Loading } from "element-ui";

export default {
  components: {
    RentList
  },
  data() {
    return {
      printSet: {
        id: "block",
        previewTitle: "充值凭证",
        popTitle: "充值凭证",
        closeCallback(vue) {
          vue.previewDialogShow = false;
        }
      },
      preViewData: {},
      previewDialogShow: false,
      searchForm: {},
      DialogVisibleSearch: false,
      pickerOptions: {
        disabledDate: time => {
          return time.getTime() > Date.now();
        }
      },
      tableData: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      total: null,
      tenantList: [],
      tenantId: "",
      productId: "",
      productSelect: [],
      time: [],
      startDate: "",
      endDate: "",
      landlordPhone: "",
      meterNumber: "",
      meterType: "",
      meterTypeList: [
        {
          label: "电表",
          value: 1
        },
        {
          label: "水表",
          value: 2
        }
      ],
      rechargeHuifuOrder: "",
      rechargeOrder: "",
      rechargeWay: [],
      rechargeWayList: [
        {
          label: "现金充值",
          value: 1
        },
        {
          label: "租币充值",
          value: 2
        },
        {
          label: "微信支付",
          value: 3
        },
        {
          label: "支付宝支付",
          value: 4
        }
      ],
      options: {
        fullscreen: true,
        text: "加载中...",
        background: "rgba(0,0,0,.5)"
      },
      activeName: "first" // 用户切换后绑定的标识
    };
  },
  created() {
    this.pageSize = Number(sessionStorage.getItem("pageSize")) || 10;
    this.pageNum = Number(sessionStorage.getItem("pageNum")) || 1;
    this.getTenant();
    this.getProductId();
    this.getTime();
    this.getRecord(
      this.pageNum,
      this.pageSize,
      this.startDate,
      this.endDate,
      this.landlordPhone,
      this.meterNumber,
      this.meterType,
      this.productId,
      this.rechargeHuifuOrder,
      this.rechargeOrder,
      this.rechargeWay,
      this.tenantId
    );

  },
  mounted() {

        // 在组件加载时模拟点击默认水电表的选项卡  
        const defaultTab = { name: 'first', label: '水电表' }; // 模拟选中的选项卡对象  
    this.handleClick(defaultTab); // 调用 handleClick 方法  
   
  },
  // 页面摧毁事件
  destroyed() {
    sessionStorage.removeItem("pageNum");
    sessionStorage.removeItem("pageSize");
    
  },
  methods: {
    //左侧 区域和分组切换的乐行
    handleClick(e) {
      console.log("切换分组和区域tab", e);
      // 判断点击的是区域选择还是分组选择
      if (e.name == "first") {
        console.log("走水电表");
        // 调用 水电表筛选
      } else {
        console.log("走租金");
        // 调用租金
 
      }
    },
    //列求和
    getSummaries(param) {
      const { columns, data } = param; //这里可以看出，自定义函数会传入每一列，以及数据
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        } else if (index == 5) {
          //index>=3后的列进行求和
          //页面分别统计 处理
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = Number(
              values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            ).toFixed(2);

            //此处结合了方式一的判断处理，实现多种条件处理
            //此处的column.property获取的值对应<el-table-column>中prop对应的字段
            switch (column.property) {
              case "total1":
              case "total2":
              case "total3":
                return (sums[index] = sums[index]);
                break;
            }
          } else {
            sums[index] = ""; //如果列的值有一项不是数字，就显示这个自定义内容
          }
        } else {
          sums[index] = "--";
        }
      });
      return sums; //最后返回合计行的数据
    },
    // 打开预览
    preview(e) {
      console.log(e);
      this.previewDialogShow = true;
      this.preViewData = e;
    },
    // 高级搜索
    searchDialog() {
      this.DialogVisibleSearch = false;
      // this.search();
    },
    // 重置
    cancelSearch() {
      this.landlordPhone = "";
      this.meterNumber = "";
      this.meterType = "";
      this.rechargeWay = "";
      this.productId = "";
    },
    closeSearch() {
      this.search();
    },
    // 查询
    search() {
      this.pageNum = 1;
      let arr = this.rechargeWay;
      if (this.rechargeWay.length !== 0) {
        this.rechargeWay = this.rechargeWay.join();
      }
      this.getRecord(
        this.pageNum,
        this.pageSize,
        this.startDate,
        this.endDate,
        this.landlordPhone,
        this.meterNumber,
        this.meterType,
        this.productId,
        this.rechargeHuifuOrder,
        this.rechargeOrder,
        this.rechargeWay,
        this.tenantId
      );
      this.rechargeWay = arr;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // 获取记录列表
    getRecord(
      pageNum,
      pageSize,
      startDate,
      endDate,
      landlordPhone,
      meterNumber,
      meterType,
      productId,
      rechargeHuifuOrder,
      rechargeOrder,
      rechargeWay,
      tenantId
    ) {
      this.loading = true;
      getRecordApi(
        pageNum,
        pageSize,
        startDate,
        endDate,
        landlordPhone,
        meterNumber,
        meterType,
        productId,
        rechargeHuifuOrder,
        rechargeOrder,
        rechargeWay,
        tenantId
      ).then(res => {
        if (res.code == 200) {
          if (res.data == null) {
            this.pageNum = this.pageNum - 1;
            if (this.pageNum > 0) {
              this.search();
            } else {
              this.loading = false;
              if (res.data) {
                this.total = res.data.total;
                this.tableData = res.data.rows;
              } else {
                this.tableData = [];
              }
            }
          } else {
            this.total = res.data.total;
            this.loading = false;
            this.tableData = res.data.rows;
          }
        }
      });
    },
    // 获取时间
    getTime() {
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;
      let day = new Date().getDate();
      let date = `${year}-${month}-${day}`;
      this.time = [date, date];
      this.startDate = date;
      this.endDate = date;
    },
    change() {
      if (this.time !== null) {
        this.startDate = this.time[0];
        this.endDate = this.time[1];
      } else {
        this.startDate = "";
        this.endDate = "";
      }
      this.search();
    },
    // 获取租户
    getTenant() {
      getTenantApi().then(res => {
        if (res.code == 200) {
          this.tenantList = res.data;
        }
      });
    },
    // 获取生产
    getProductId() {
      getProductIdApi().then(res => {
        if (res.code == 200) {
          this.productSelect = res.data;
        }
      });
    },
    // 分页 pagesize
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageNum = 1;
      let arr = this.rechargeWay;
      if (this.rechargeWay.length !== 0) {
        this.rechargeWay = this.rechargeWay.join();
      }
      this.getRecord(
        this.pageNum,
        val,
        this.startDate,
        this.endDate,
        this.landlordPhone,
        this.meterNumber,
        this.meterType,
        this.productId,
        this.rechargeHuifuOrder,
        this.rechargeOrder,
        this.rechargeWay,
        this.tenantId
      );
      this.rechargeWay = arr;
      sessionStorage.setItem("pageSize", val);
      this.pageSize = val;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // pageNum
    handleCurrentChange(val) {
      let arr = this.rechargeWay;
      if (this.rechargeWay.length !== 0) {
        this.rechargeWay = this.rechargeWay.join();
      }
      this.getRecord(
        val,
        this.pageSize,
        this.startDate,
        this.endDate,
        this.landlordPhone,
        this.meterNumber,
        this.meterType,
        this.productId,
        this.rechargeHuifuOrder,
        this.rechargeOrder,
        this.rechargeWay,
        this.tenantId
      );
      this.rechargeWay = arr;
      sessionStorage.setItem("pageNum", val);
      this.pageNum = val;
      this.$refs.isExpand.bodyWrapper.scrollTop = 0;
    },
    // 导出
    async out() {
      let arr = this.rechargeWay;
      if (this.rechargeWay.length !== 0) {
        this.rechargeWay = this.rechargeWay.join();
      }
      Loading.service(this.options);
      await outOrderApi(
        this.pageNum,
        this.pageSize,
        this.startDate,
        this.endDate,
        this.landlordPhone,
        this.meterNumber,
        this.meterType,
        this.productId,
        this.rechargeHuifuOrder,
        this.rechargeOrder,
        this.rechargeWay,
        this.tenantId
      )
        .then(res => {
          Loading.service(this.options).close();
          if (
            res.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          ) {
            let blob = new Blob([res], { type: "application/octet-stream" });
            const link = document.createElement("a");
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            link.setAttribute("download", "交易记录.xlsx");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
        .catch(err => {
          Loading.service(this.options).close();
          console.log(err);
        });
      this.rechargeWay = arr;
    }
  }
};
</script>

<style lang="scss" scoped>
.record1 {
  // padding-top: 15px;
  padding: 15px;
  // height: calc(100vh - 100px);
  height: 100%;
  overflow: scroll;
  box-sizing: border-box;
  .search {
    margin-bottom: 15px;

    .elInput {
      width: 200px;
      margin: 5px;
    }

    .el-select {
      box-sizing: border-box;
      width: 200px;
      margin: 5px;
    }

    .el-button {
      margin-left: 15px;
    }
  }

  .table {
    // height: 90%;

    .el-table {
      // height: 80%;
      // overflow: auto;
    }

    .el-pagination {
      text-align: center;
      margin-top: 20px;
    }
  }

  .previewDialog {
    .el-dialog {
      height: 60%;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      .el-dialog__body {
        height: 90%;
      }
    }
  }

  .searchMore {
    .el-dialog {
      .el-dialog__body {
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
      }
    }
  }
}
</style>
<style>
.twoLineCls1 {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
}
</style>
